package com.projecy.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projecy.common.exception.BadRequestException;
import com.projecy.system.mapper.SysRoleMapper;
import com.projecy.system.model.SysRole;
import com.projecy.system.model.SysRoleUser;
import com.projecy.system.service.SysRoleMenuService;
import com.projecy.system.service.SysRoleService;
import com.projecy.system.service.SysRoleUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    SysRoleMapper roleMapper;
    @Autowired
    SysRoleUserService roleUserService;
    @Autowired
    SysRoleMenuService roleMenuService;


    @Override//获取角色列表
    public List<SysRole> getRoleList(String blurry) {
        System.out.println("获取角色列表");
        try {
            LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(blurry)){
                wrapper.like(SysRole::getRoleName, blurry);
                wrapper.or();
                wrapper.like(SysRole::getRoleCode, blurry);
                wrapper.or();
                wrapper.like(SysRole::getDescription, blurry);
            }
            return roleMapper.selectList(wrapper);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override//编辑角色
    public void editRole(SysRole role) {
        System.out.println("编辑角色");
        try {
            //  校验角色代码及名称
            checkRole(role);
            if (role.getId() != null){
                roleMapper.updateById(role);
            } else {
                roleMapper.insert(role);
            }
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    @Transactional
    public void delRole(Long id) {//删除角色
        System.out.println("删除角色");
        try {
            //  校验角色是否已绑定用户
            checkRoleUser(id);
            //  先把与角色绑定的菜单删除
            roleMenuService.deleteByRoleId(id);
            //  再删除角色
            roleMapper.deleteById(id);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    public JSONArray getAllRoleForXm(Long userId) {//角色选择框列表
        System.out.println("角色选择框列表");
        try {
            //  查询所有角色
            List<SysRole> list = roleMapper.selectList(null);
            //  查询当前用户角色
            List<SysRoleUser> roleUserList = roleUserService.getRoleUserByUserId(userId);
            JSONArray jsonArray = new JSONArray();
            if (!CollectionUtils.isEmpty(list)){
                for (SysRole role : list) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", role.getRoleName());
                    jsonObject.put("id", role.getId());

                    if (!CollectionUtils.isEmpty(roleUserList) && roleUserList.get(0).getRoleId().equals(role.getId())){
                        jsonObject.put("selected", true);
                    }
                    jsonArray.add(jsonObject);
                }
            }
            return jsonArray;
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    public List<SysRole> getRoleByUserId(Long userId) {//通过用户ID获取当前用户角色
        System.out.println("通过用户ID获取当前用户角色");
        try {
            return roleMapper.getRoleByUserId(userId);
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    @Override
    public List<GrantedAuthority> getRolesByUser(Long userId) {//获取用户当前角色列表
        System.out.println("获取用户当前角色列表");
        Set<String> permissions = new HashSet<>();
        System.out.println("userId====>"+userId);
        List<SysRole> roleList = roleMapper.getRoleByUserId(userId);
        System.out.println("roleList====>"+roleList);
        if (!CollectionUtils.isEmpty(roleList)){
            for (SysRole sysRole : roleList) {
                permissions.add(sysRole.getRoleCode());
                System.out.println("permissions====>"+permissions);
            }
        }
        System.out.println("permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())"+permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }


    private void checkRole(SysRole role){//校验角色名称和代码
        System.out.println("校验角色名称和代码");
        try {
            List<SysRole> list;
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            if (role.getId() != null){
                wrapper.ne("id", role.getId());
            }
            wrapper.and(w -> w.eq("role_name", role.getRoleName()).or().eq("role_code", role.getRoleCode()));
            list = roleMapper.selectList(wrapper);
            if (list != null && !list.isEmpty()){
                throw new BadRequestException("角色代码或名称已存在，请重新输入");
            }
        } catch (BadRequestException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMsg());
        }
    }


    private void checkRoleUser(Long roleId){//校验角色是否已绑定用户
        System.out.println("校验角色是否已绑定用户");
        List<SysRoleUser> list = roleUserService.getRoleUserByRoleId(roleId);
        if (!CollectionUtils.isEmpty(list)){
            throw new BadRequestException("该角色已绑定用户，请解绑后再删除");
        }
    }
}
